package services;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.RegistrationRepository;
import domain.Event;
import domain.Registration;

@Service
@Transactional
public class RegistrationService {
	@Autowired
	private RegistrationRepository registrationRepository;
	@Autowired
	private ParticipantService participantService;

	public RegistrationService() {
		super();
	}

	public Registration create(Event event) {
		Assert.notNull(event);
		Registration registration = new Registration();
		registration.setParticipant(participantService.findByPrincipal());
		registration.setRegistrationDate(new Date());
		registration.setEvent(event);

		return registration;
	}

	public void save(Registration registration) {
		Assert.notNull(registration);
		registrationRepository.save(registration);
	}

	public void delete(Registration registration) {
		Assert.notNull(registration);
		Assert.isTrue(registration.getId() != 0);
		Assert.isTrue(registrationRepository.exists(registration.getId()));
		Assert.isTrue(registration.getParticipant().equals(
				participantService.findByPrincipal()));
		Assert.isTrue(new Date().compareTo(registration.getEvent()
				.getStartMoment()) < 1);

		registrationRepository.delete(registration);
	}

	public Registration getRegistrationForEvent(int participantId, int eventId) {
		Assert.isTrue(participantId != 0 && eventId != 0);
		Registration result = registrationRepository.IsRegisteredForEvent(
				participantId, eventId);

		return result;

	}

	public Boolean IsRegisteredForEvent(int participantId, int eventId) {
		Assert.isTrue(participantId != 0 && eventId != 0);
		Registration result = registrationRepository.IsRegisteredForEvent(
				participantId, eventId);

		Boolean registered = false;
		if (result != null) {
			registered = true;
		}

		return registered;

	}

	public Registration findOne(int registrationId) {

		Assert.isTrue(registrationId != 0);
		Registration result;
		result = registrationRepository.findOne(registrationId);
		Assert.notNull(result);

		return result;
	}

}
